package com.p2p.common.interceptor;

import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * Created by lizhuolun on 2016/8/30.
 */
public abstract class BaseInterceptor extends HandlerInterceptorAdapter {

    private static final Logger logger = LoggerFactory.getLogger(BaseInterceptor.class);
    private static final PathMatcher PATH_MATCHER = new AntPathMatcher();
    private List<String> excludePattern;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (this.isExcludeURL(request)) {
            return true;
        }

        return this.doPreHandle(request, response, handler);
    }

    protected abstract boolean doPreHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception;

    /**
     * 判断是否不拦截的URL
     */
    protected boolean isExcludeURL(HttpServletRequest request) {
        if (CollectionUtils.isEmpty(this.excludePattern)) {
            return false;
        }

        String requestURI = request.getRequestURI();
        for (String pattern : excludePattern) {
            if (PATH_MATCHER.match(pattern, requestURI)) {
                logger.debug("RequestURI {} is matched excludePattern: {}", requestURI, excludePattern);
                return true;
            }
        }

        return false;
    }

    public List<String> getExcludePattern() {
        return excludePattern;
    }

    public void setExcludePattern(List<String> excludePattern) {
        this.excludePattern = excludePattern;
    }
}

